using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.FormsManagement;
using PHSRAG.Insight21.Policy;
using PHSRAG.Utility;

namespace PHSRAG.Insight21.Humans
{
    /// <summary>
    /// DrugSelectionPage lets the user search or add existing or new drugs to the protocol.
    /// 
    /// Additions of new drugs is only possible after completing at least one search
    /// </summary>
    public partial class DrugSelectionPage : BasePage
    {
        #region Constants

        private const string AnnunciatorTitle = "The following error(s) occurred...";
        private const string DrugsKey = "drugs_12589E7F-CC7F-4e95-A0FB-E7086E014900";
        private const string PageCacheKey = "DrugSelectionPage_12589E7F-CC7F-4e95-A0FB-E7086E014900";
        private const string ProtocolAccessLevelKey = "protocolAccessLevel_19D02A27-A07F-4984-934F-785476927A26";
        private const string ProtocolIdKey = "ProtocolId_12589E7F-CC7F-4e95-A0FB-E7086E014900";
        private const string ProtocolProcessIdKey = "PPId_12589E7F-CC7F-4e95-A0FB-E7086E014900";
        private const string ProtocolVersionIdKey = "PVId_12589E7F-CC7F-4e95-A0FB-E7086E014900";
        private const string QuestionnaireAnswerIdKey = "QAId_12589E7F-CC7F-4e95-A0FB-E7086E014900";

        #endregion

        #region instance fields

        private ICachePolicy cachePolicy;
        private Hashtable pageCache;
        private ICachePolicy pageCachePolicy;
        private Protocol protocol;
        private int protocolId;
        private ProtocolProcess protocolProcess;
        private int protocolProcessId;
        private int pVersionId;
        private int qAnswerId;
        private QuestionnaireAnswer questionnaireAnswer;
        private bool removeQAOnCancel;

        //This flag is used to decide whether or not the headers should be displayed
        //If the page is to be displayed as a popup, then the header section is made invisible
        private bool showAsPopUp = false;
        private int userAccessLevel;

        #endregion

        #region Properties

        /// <summary>
        /// Gets the protocol for which staffing is being reviewed or modified.  If it's not already
        /// in the cache, it loads it up based on the protocolId passed to the page, and caches the object
        /// </summary>
        private Protocol Protocol
        {
            get
            {
                string cacheKey = Protocol.ProtocolKey;
                protocol = cachePolicy.GetCachedObject(cacheKey) as Protocol;

                if ((protocol == null) || (protocolId != protocol.Id))
                {
                    protocol = new Protocol(cachePolicy);
                    protocol.Load(DataAccess.GetConnectionString(), protocolId);
                    cachePolicy.Cache(cacheKey, protocol);
                }
                return protocol;
            }
        }

        /// <summary>
        /// Gets the protocol process for which staffing is being reviewed or modified.  If it's not already
        /// in the cache, it loads it up based on the protocolProcessId passed to the page, and caches the 
        /// object
        /// </summary>
        private ProtocolProcess ProtocolProcess
        {
            get
            {
                protocolProcess = cachePolicy.GetCachedObject(ProtocolProcess.ProtocolProcessKey)
                    as ProtocolProcess;

                if ((protocolProcess == null) || (protocolProcessId != protocolProcess.Id))
                {
                    if (protocolProcessId > 0)
                    {
                        protocolProcess = ProtocolProcess.GetProtocolProcess(
                            DataAccess.GetConnectionString(), protocolProcessId, cachePolicy, null);
                        cachePolicy.Cache(ProtocolProcess.ProtocolProcessKey, protocolProcess);
                    }
                    else
                    {
                        protocolProcess = null;
                    }
                }
                return protocolProcess;
            }
        }

        #endregion

        #region Page Events

        /// <summary>
        /// Loads the page. Initializes the breadcrumb. Pulls the data from incoming cache and stores them in the page cache.
        /// Loads the drug types from the database into a dropdownlist
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnPageLoad(object sender, EventArgs e)
        {
            try
            {
                breadCrumb.Add(
                    "Agent Selection",
                    Settings.GetKeyValue("SubModuleNavigation.Humans.DrugSelectionPageURL", ""),
                    Settings.GetKeyValue("BreadCrumb.DetailPageLevel", 2));

                pageCache = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();

                annunciator.Message = string.Empty;

                if (! IsPostBack)
                {
                    Hashtable incomingPageHash = pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                    if (incomingPageHash != null)
                    {
                        userAccessLevel = Convert.ToInt32(incomingPageHash[Keys.ProtocolAccessKey]);

                        protocolId = Convert.ToInt32(incomingPageHash[Keys.ProtocolIdKey]);
                        pageCache[ProtocolIdKey] = protocolId;

                        protocol = new Protocol(cachePolicy);
                        protocol.Load(DataAccess.ConnectionString, protocolId);
                        protocol.Cache();

                        pVersionId = Convert.ToInt32(incomingPageHash[Keys.ProtocolVersionIdKey]);
                        pageCache[ProtocolVersionIdKey] = pVersionId;

                        qAnswerId = Convert.ToInt32(incomingPageHash[Keys.QuesionnaireAnswerIdKey]);
                        pageCache[QuestionnaireAnswerIdKey] = qAnswerId;
                        questionnaireAnswer = new QuestionnaireAnswer(cachePolicy);
                        questionnaireAnswer.Load(DataAccess.ConnectionString, qAnswerId);
                        questionnaireAnswer.Cache();

                        protocolProcessId = Convert.ToInt32(incomingPageHash[Keys.ProtocolProcessIdKey]);
                        pageCache[ProtocolProcessIdKey] = protocolProcessId;

                        protocolProcess = ProtocolProcess.GetProtocolProcess(DataAccess.ConnectionString,
                            protocolProcessId, cachePolicy, null);

                        protocolProcess.Cache();

                        if (incomingPageHash.ContainsKey(Keys.ShowAsPopUp))
                        {
                            showAsPopUp = Convert.ToBoolean(incomingPageHash[Keys.ShowAsPopUp]);
                        }
                        pageCache[Keys.ShowAsPopUp] = showAsPopUp;

                        if (incomingPageHash.ContainsKey(Keys.RemoveQAOnCancel))
                        {
                            removeQAOnCancel = Convert.ToBoolean(incomingPageHash[Keys.RemoveQAOnCancel]);
                            pageCache[Keys.RemoveQAOnCancel] = removeQAOnCancel;
                        }

                        pageCache[ProtocolAccessLevelKey] = userAccessLevel;

                        pageCachePolicy.Cache(PageCacheKey, pageCache);
                        pageCachePolicy.UnCache(Keys.IncomingDataKey);
                    }
                    else
                    {
                        userAccessLevel = (int) pageCache[ProtocolAccessLevelKey];
                        protocolId = (int) pageCache[ProtocolIdKey];
                        pVersionId = (int) pageCache[ProtocolVersionIdKey];
                        qAnswerId = (int) pageCache[QuestionnaireAnswerIdKey];
                        protocolProcessId = (int) pageCache[ProtocolProcessIdKey];
                        showAsPopUp = (bool) pageCache[Keys.ShowAsPopUp];
                        removeQAOnCancel = (bool) pageCache[Keys.RemoveQAOnCancel];
                        questionnaireAnswer = new QuestionnaireAnswer(cachePolicy);
                        questionnaireAnswer = (QuestionnaireAnswer) cachePolicy.GetCachedObject(questionnaireAnswer.CacheKey());

                        protocolProcess = (ProtocolProcess) cachePolicy.GetCachedObject(ProtocolProcess.ProtocolProcessKey);
                    }
                    LoadDrugTypes();
                }
                else
                {
                    userAccessLevel = (int) pageCache[ProtocolAccessLevelKey];
                    protocolId = (int) pageCache[ProtocolIdKey];
                    pVersionId = (int) pageCache[ProtocolVersionIdKey];
                    qAnswerId = (int) pageCache[QuestionnaireAnswerIdKey];
                    protocolProcessId = (int) pageCache[ProtocolProcessIdKey];
                    showAsPopUp = (bool) pageCache[Keys.ShowAsPopUp];
                    removeQAOnCancel = (bool) pageCache[Keys.RemoveQAOnCancel];
                    questionnaireAnswer = new QuestionnaireAnswer(cachePolicy);
                    questionnaireAnswer = (QuestionnaireAnswer) cachePolicy.GetCachedObject(questionnaireAnswer.CacheKey());

                    protocolProcess = (ProtocolProcess) cachePolicy.GetCachedObject(ProtocolProcess.ProtocolProcessKey);
                }

                //if page is being shown as popup, then hide the header section
                headerSection.Visible = !showAsPopUp;
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
            finally
            {
                protocolDetailHeader.ProtocolID = protocolId;
                //Set the humansubmodule Navigation links
                humansSubModNavigation.ProtocolProcess = ProtocolProcess;
                humansSubModNavigation.Protocol = Protocol;
            }
        }

        #endregion

        #region Web Form Designer generated code

        /// <summary>
        /// Page Initialization
        /// </summary>
        /// <param name="e">Arguments associated with the event.</param>
        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.header.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnNavigate);
            this.humansSubModNavigation.Navigate += new PHSRAG.Insight21.InsightWebControls.HumansSubModuleNavigation.NavigateEventHandler(this.OnHumansSubModNavigate);
            this.breadCrumb.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnBreadCrumbNavigate);
            this.searchDrug.Click += new ImageClickEventHandler(OnSearchDrugClick);
            this.cancel.Click += new ImageClickEventHandler(OnCancel);
            this.next.Click += new ImageClickEventHandler(OnNextClick);
            this.Load += new System.EventHandler(this.OnPageLoad);
        }

        #endregion

        #region Control Events

        /// <summary>
        /// Resets the subnavigation selected link before the breadCrumb performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnBreadCrumbNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                humansSubModNavigation.Reset();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Resets the subnavigation selected link before the header or the breadCrumb performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                humansSubModNavigation.Reset();
                humansSubNavigation.Reset();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Constructs and caches a hashtable of data for use by the page to which nagivation leads
        /// </summary>
        private void OnHumansSubModNavigate()
        {
            try
            {
                Hashtable outgoingData = new Hashtable();
                outgoingData.Add(Keys.ProtocolAccessKey, userAccessLevel);
                outgoingData.Add(Keys.ProtocolIdKey, protocolId);
                outgoingData.Add(Keys.ProtocolProcessIdKey, protocolProcessId);
                outgoingData.Add(Keys.ProtocolVersionIdKey, pVersionId);
                outgoingData.Add(Keys.QuesionnaireAnswerIdKey, qAnswerId);
                pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Search for drug(s) based on the selected nameType and the drug name entered.
        /// The list of drugs found are populated into a dropdownlist with their selected name types and the manufacturer (enclosed in square brackets)
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnSearchDrugClick(object sender, ImageClickEventArgs e)
        {
            next.Visible = true;
            addDrug.Enabled = true;
            Drugs drugCollection = new Drugs(cachePolicy);
            string invName = string.Empty, markName = string.Empty, genName = string.Empty;
            drugList.Items.Clear();
            switch (nameType.SelectedIndex)
            {
                case 0:
                    invName = drugName.Text.Trim();
                    drugCollection.SortBy = Drugs.SortByColumn.ItemName;
                    break;
                case 1:
                    markName = drugName.Text.Trim();
                    drugCollection.SortBy = Drugs.SortByColumn.MarketingName;
                    break;
                case 2:
                    genName = drugName.Text.Trim();
                    drugCollection.SortBy = Drugs.SortByColumn.GenericName;
                    break;
            }
            drugCollection.Load(DataAccess.GetConnectionString(InsightUtilities.Constants.RexDatabaseKey),
                invName, genName, markName, string.Empty, string.Empty, string.Empty, false, false);

            if (drugCollection.DrugList.Count > 0)
            {
                pickOne.Visible = true;
                drugList.Visible = true;
                cachePolicy.Cache(DrugsKey, drugCollection);

                switch (nameType.SelectedIndex)
                {
                    case 0:
                        foreach (Drug d in drugCollection.DrugList)
                        {
                            drugList.Items.Add(d.InvestigationalName + "  [" + d.Manufacturer.ToUpper() + "]");
                        }
                        break;
                    case 1:
                        foreach (Drug d in drugCollection.DrugList)
                        {
                            drugList.Items.Add(d.MarketingName + "  [" + d.Manufacturer.ToUpper() + "]");
                        }
                        break;
                    case 2:
                        foreach (Drug d in drugCollection.DrugList)
                        {
                            drugList.Items.Add(d.GenericName + "  [" + d.Manufacturer.ToUpper() + "]");
                        }
                        break;
                }
            }
            else
            {
                annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
                annunciator.Message = "No results are found.  Please search again or click the \"Add New Agent\" check box then click \"Next\" to enter an agent not found.";
                pickOne.Visible = false;
                drugList.Visible = false;
            }
        }

        /// <summary>
        /// The nameType radiobuttonlist posts back only the first time the user selects an option.
        /// This eventhandler enables the search button and sets the autopostback property on the radiobuttonlist to false.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnNameTypeSelectedIndexChanged(object sender, EventArgs e)
        {
            searchDrug.Visible = true;
            nameType.AutoPostBack = false;
        }

        /// <summary>
        /// If the addDrug checkbox is checked, then a new drug is added to the database.
        /// The questionnaire answer's name is set to the name of the drug selected or being added.
        /// The drugs questionnaire is shown to the user with the manufacturer question set to 
        /// the value entered/selected by the user. 
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnNextClick(object sender, ImageClickEventArgs e)
        {
            //TODO: might have to move to script
            Answer manufacturerAnswer = new Answer(cachePolicy);
            manufacturerAnswer.Name = "Manufacturer";
            manufacturerAnswer.QuestionnaireAnswerId = questionnaireAnswer.Id;

            Answer typeAgentAnswer = new Answer(cachePolicy);
            typeAgentAnswer.Name = "TypeAgent";
            typeAgentAnswer.QuestionnaireAnswerId = questionnaireAnswer.Id;

            if (addDrug.Checked)
            {
                if (!ValidateNewDrugInput())
                {
                    return;
                }
                Drug newDrug = new Drug(cachePolicy);
                newDrug.GenericName = newGenericName.Text.Trim();
                newDrug.InvestigationalName = newInvestigationalName.Text.Trim();
                newDrug.MarketingName = newMarketingName.Text.Trim();
                newDrug.Manufacturer = newDrugManufacturer.Text.Trim();
                newDrug.Type = newDrugType.SelectedItem.Text;
                newDrug.BiologicClass = string.Empty;
                newDrug.AddRequest(DataAccess.ConnectionString, DataAccess.GetConnectionString(InsightUtilities.Constants.RexDatabaseKey), protocolProcess.Id);
                questionnaireAnswer.ExternalId = newDrug.Id;

                switch (newDrugNameType.SelectedIndex)
                {
                    case 0:
                        questionnaireAnswer.Name = newInvestigationalName.Text.Trim();
                        break;
                    case 1:
                        questionnaireAnswer.Name = newMarketingName.Text.Trim();
                        break;
                    case 2:
                        questionnaireAnswer.Name = newGenericName.Text.Trim();
                        break;
                }

                manufacturerAnswer.Value = newDrugManufacturer.Text.Trim();

                switch (newDrug.Type)
                {
                    case "Biologic":
                        typeAgentAnswer.Value = "TypeBiologic";
                        break;
                    case "Dietary Supplement":
                        typeAgentAnswer.Value = "TypeDietary";
                        break;
                    case "Drug":
                        typeAgentAnswer.Value = "TypeDrug";
                        break;
                    case "Stable Isotope":
                        typeAgentAnswer.Value = "TypeIsotope";
                        break;
                }
            }
            else
            {
                if (drugList.Items.Count == 0)
                {
                    annunciator.Message = "No results are found.  Please search again or click the \"Add New Agent\" check box then click \"Next\" to enter an agent not found.";
                    return;
                }

                if (drugList.SelectedIndex == -1)
                {
                    annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
                    annunciator.Message = "No agent is selected.";
                    return;
                }

                string nameAndMfc = drugList.SelectedItem.Text;
                questionnaireAnswer.Name = nameAndMfc.Substring(0, nameAndMfc.IndexOf('[') - 1).Trim();
                int startIndex = nameAndMfc.IndexOf('[') + 1;
                manufacturerAnswer.Value = nameAndMfc.Substring(startIndex, nameAndMfc.IndexOf(']') - startIndex);

                Drugs drugCollection = (Drugs) cachePolicy.GetCachedObject(DrugsKey);

                if (drugCollection.DrugList.Count > 0)
                {
                    string drugType = string.Empty;
                    switch (nameType.SelectedIndex)
                    {
                        case 0:
                            foreach (Drug d in drugCollection.DrugList)
                            {
                                if (d.InvestigationalName == questionnaireAnswer.Name)
                                {
                                    drugType = d.Type;
                                    questionnaireAnswer.ExternalId = d.Id;
                                    break;
                                }
                            }
                            break;
                        case 1:
                            foreach (Drug d in drugCollection.DrugList)
                            {
                                if (d.MarketingName == questionnaireAnswer.Name)
                                {
                                    drugType = d.Type;
                                    questionnaireAnswer.ExternalId = d.Id;
                                    break;
                                }
                            }
                            break;
                        case 2:
                            foreach (Drug d in drugCollection.DrugList)
                            {
                                if (d.GenericName == questionnaireAnswer.Name)
                                {
                                    drugType = d.Type;
                                    questionnaireAnswer.ExternalId = d.Id;
                                    break;
                                }
                            }
                            break;
                    }

                    switch (drugType)
                    {
                        case "Biologic":
                            typeAgentAnswer.Value = "TypeBiologic";
                            break;
                        case "Dietary Supplement":
                            typeAgentAnswer.Value = "TypeDietary";
                            break;
                        case "Drug":
                            typeAgentAnswer.Value = "TypeDrug";
                            break;
                        case "Stable Isotope":
                            typeAgentAnswer.Value = "TypeIsotope";
                            break;
                    }
                }
            }
            questionnaireAnswer.Answers.Add(manufacturerAnswer);
            questionnaireAnswer.Answers.Add(typeAgentAnswer);
            //Add the admPersonId of the user last modified or added the drug
            UserContext loggedInUserContext = cachePolicy.GetCachedObject(UserContext.CacheKey) as UserContext;
            questionnaireAnswer.LastModifiedByAdmPersonId = loggedInUserContext.PersonId;

            questionnaireAnswer.Save(DataAccess.ConnectionString);


            Hashtable outgoingData = new Hashtable();
            outgoingData.Add(Keys.ProtocolAccessKey, userAccessLevel);
            outgoingData.Add(Keys.ProtocolIdKey, protocolId);
            outgoingData.Add(Keys.ProtocolProcessIdKey, protocolProcessId);
            outgoingData.Add(Keys.ProtocolVersionIdKey, pVersionId);
            outgoingData.Add(Keys.QuestionnaireVersionIdKey, questionnaireAnswer.QuestionnaireVersionId);
            outgoingData.Add(Keys.QuesionnaireAnswerIdKey, questionnaireAnswer.Id);
            outgoingData.Add(Keys.ShowAsPopUp, showAsPopUp);
            pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);
            Page.Response.Redirect(Settings.GetKeyValue("SubModuleNavigation.Humans.AnswerQuestionnairePageURL", ""));
        }

        /// <summary>
        /// Navigates to the ProtocolProcessOverview page
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnCancel(object sender, ImageClickEventArgs e)
        {
            if (removeQAOnCancel)
            {
                ProtocolVersion pV = new ProtocolVersion(cachePolicy);
                pV.Load(DataAccess.ConnectionString, pVersionId);
                pV.DeleteQuestionnaireAnswer(questionnaireAnswer.Id);
            }

            Hashtable outgoingData = new Hashtable();
            outgoingData.Add(Keys.ProtocolIdKey, protocolId);
            outgoingData.Add(Keys.ProtocolProcessIdKey, protocolProcessId);
            outgoingData.Add(Keys.ProtocolAccessKey, userAccessLevel);
            outgoingData.Add(Keys.ShowAsPopUp, showAsPopUp);
            pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);

            if (!showAsPopUp)
            {
                Response.Redirect(Settings.GetKeyValue("SubModuleNavigation.Humans.ProtocolProcessOverviewURL", ""));
            }
            else
            {
                ClientScript.RegisterStartupScript(GetType(), "CloseWindow", "<script>javascript:window.close();</script>");
            }
        }

        /// <summary>
        /// If checked, clears all the search critieria and displays UI for adding a new drug.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnAddDrugCheckedChanged(object sender, EventArgs e)
        {
            if (addDrug.Checked)
            {
                nameType.SelectedIndex = -1;
                drugName.Text = string.Empty;
                searchDrug.Visible = false;
                pickOne.Visible = false;
                drugList.Items.Clear();
                drugList.Visible = false;
                newDrugDetails.Visible = true;
                searchSection.Enabled = false;
            }
            else
            {
                searchSection.Enabled = true;
                newDrugDetails.Visible = false;
            }
        }

        #endregion

        #region Private methods

        /// <summary>
        /// Displays an error message on the screen to the user with the exception, and all
        /// inner exception messages.
        /// </summary>
        /// <param name="ex">The exception to report on</param>
        private void DisplayExceptionReport(Exception ex)
        {
            annunciator.Title = AnnunciatorTitle;
            annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
        }

        /// <summary>
        /// Checks if one of the 3 names for the drug and the manufacturer are entered.
        /// </summary>
        /// <returns>true, if one of the 3 names and the manufacturer are entered</returns>
        private bool ValidateNewDrugInput()
        {
            if (newDrugNameType.SelectedIndex == 0 && newInvestigationalName.Text.Trim() == string.Empty)
            {
                annunciator.Title = AnnunciatorTitle;
                annunciator.Message = "Enter Investigational Product Name (Manufacturer's Designation) for the new drug";
                return false;
            }
            if (newDrugNameType.SelectedIndex == 1 && newMarketingName.Text.Trim() == string.Empty)
            {
                annunciator.Title = AnnunciatorTitle;
                annunciator.Message = "Enter Marketed Product Name (Manufacturer Proprietary Trade/Brand Name) for the new drug";
                return false;
            }
            if (newDrugNameType.SelectedIndex == 2 && newGenericName.Text.Trim() == string.Empty)
            {
                annunciator.Title = AnnunciatorTitle;
                annunciator.Message = "Enter Marketed Product Generic Name for the new drug";
                return false;
            }
            if (newDrugManufacturer.Text.Trim() == string.Empty)
            {
                annunciator.Title = AnnunciatorTitle;
                annunciator.Message = "Enter the Manufacturer Name of the Drug";
                return false;
            }
            return true;
        }

        /// <summary>
        /// Loads all types of the drugs in a dropdownlist.
        /// 
        /// To facilitate for a no-selection scenario, a blank entry is inserted into the arraylist 
        /// holding drug types before it is bound to the dropdown provided for searching drugs.
        /// </summary>
        private void LoadDrugTypes()
        {
            Drugs drugs = new Drugs(cachePolicy);
            ArrayList drugTypeList = drugs.GetDrugTypes(DataAccess.GetConnectionString(InsightUtilities.Constants.RexDatabaseKey));
            newDrugType.DataSource = drugTypeList;
            newDrugType.DataBind();
        }

        #endregion
    }
}